package com.tanhua.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName: MyMetaObjectHandler
 * @Author:王晨晗
 * @Description: mybatis-plus对自动填充字段的处理类
 * @Date: 2021/12/25/18:43
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        //获取created属性
        Object created = getFieldValByName("created", metaObject);
        if (created == null){           //判断created是否为空
            //条件成立 , 表示第一次创建 , 可以赋值
            setFieldValByName("created" , new Date() , metaObject);
        }

        //获取updated属性值
        Object updated = getFieldValByName("updated", metaObject);
        if (updated == null){
            //字段为空 进行赋值
            setFieldValByName("updated"  , new Date() , metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //更新修改时间 , 直接赋值
        setFieldValByName("updated" , new Date() , metaObject);
    }
}
